package model

import (
	"gin-vben-admin/internal/constant"
	"gorm.io/gorm"
	"strconv"
	"strings"
	"time"
)

type SysDept struct {
	DeptId   int64  `json:"dept_id" gorm:"primaryKey;autoIncrement;comment:主键编码"`             //部门id
	ParentId int64  `json:"parent_id" gorm:"column:parent_id;notNull;default:0;comment:父级id"` //部门父id
	DeptName string `json:"dept_name" gorm:"column:dept_name;size:100;notNull;comment:部门名称"`  //部门名称
	IdPath   string `json:"id_path" gorm:"column:id_path;size:255;notNull;comment:父级路径"`

	Sort      int             `json:"sort" gorm:"column:sort;notNull;default:0;comment:排序，小到大"`        //排序
	Remark    string          `json:"remark" gorm:"column:remark;notNull;default:'';comment:备注"`       //备注
	Status    constant.Status `json:"status" gorm:"column:status;notNull;default:1;comment:状态"`        //状态 1启用2禁用
	CreateBy  int64           `json:"create_by" gorm:"column:create_by;notNull;default:0;comment:创建者"` //创建者
	UpdateBy  int64           `json:"update_by" gorm:"column:update_by;notNull;default:0;comment:更新者"` //最后更新者
	CreatedAt time.Time       `json:"created_at" gorm:"column:created_at;type:datetime;notNull"`
	UpdatedAt time.Time       `json:"updated_at" gorm:"column:updated_at;type:datetime;notNull"`
	DeletedAt gorm.DeletedAt  `json:"-" gorm:"column:deleted_at;index;"`

	Children []*SysDept `json:"children,omitempty" gorm:"-"` //子部门
}

func (s *SysDept) TableName() string {
	return "sys_dept"
}

// ParseIdPath 把 IdPath 解析成数组
func (s *SysDept) ParseIdPath(hasSelf bool) (res []int64) {
	sArr := strings.Split(s.IdPath, "/")
	for _, v := range sArr {
		if i, err := strconv.Atoi(v); err == nil && i > 0 {
			res = append(res, int64(i))
		}
	}
	if hasSelf {
		res = append(res, s.DeptId)
	}
	return
}
